package com.bookrecomm.controller;

import com.bookrecomm.entity.Book;
import com.bookrecomm.service.RecommendationService;
import com.bookrecomm.vo.BookVO;
import com.bookrecomm.vo.PageVO;
import com.bookrecomm.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 图书推荐控制器
 * 处理所有与图书推荐相关的请求
 */
@RestController
@RequestMapping("/recommendations")
public class RecommendationController {

    @Autowired
    private RecommendationService recommendationService;

    /**
     * 获取热门图书推荐
     * @param page 页码
     * @param size 每页数量
     * @return 热门图书列表
     */
    @GetMapping("/hot")
    public ResultVO<PageVO<BookVO>> getHotBooks(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageVO<Book> hotBooks = recommendationService.getHotBooks(page, size);
            
            // 转换为VO对象
            List<BookVO> bookVOList = hotBooks.getList().stream()
                    .map(this::convertToBookVO)
                    .collect(Collectors.toList());
            
            PageVO<BookVO> result = new PageVO<>();
            result.setList(bookVOList);
            result.setTotal(hotBooks.getTotal());
            // 设置页码和每页大小
            result.setPageNum(page);
            result.setPageSize(size);
            
            return ResultVO.success(result);
        } catch (Exception e) {
            return ResultVO.clientError("获取热门图书失败: " + e.getMessage());
        }
    }

    /**
     * 获取分类下的热门图书
     * @param categoryId 分类ID，可以是具体的分类ID或者特殊值"all"表示所有分类
     * @param page 页码
     * @param size 每页数量
     * @return 分类下的热门图书
     */
    @GetMapping("/hot/category/{categoryId}")
    public ResultVO<PageVO<BookVO>> getHotBooksByCategory(
            @PathVariable String categoryId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageVO<Book> hotBooks;
            
            // 判断是否是特殊值"all"
            if ("all".equalsIgnoreCase(categoryId)) {
                // 获取所有分类的热门图书
                hotBooks = recommendationService.getHotBooks(page, size);
            } else {
                // 转换为Long类型并获取指定分类的热门图书
                try {
                    Long categoryIdLong = Long.parseLong(categoryId);
                    hotBooks = recommendationService.getHotBooksByCategory(categoryIdLong, page, size);
                } catch (NumberFormatException e) {
                    return ResultVO.clientError("分类ID格式不正确，应为数字或'all'");
                }
            }
            
            // 转换为VO对象
            List<BookVO> bookVOList = hotBooks.getList().stream()
                    .map(this::convertToBookVO)
                    .collect(Collectors.toList());
            
            PageVO<BookVO> result = new PageVO<>();
            result.setList(bookVOList);
            result.setTotal(hotBooks.getTotal());
            // 设置页码和每页大小
            result.setPageNum(page);
            result.setPageSize(size);
            
            return ResultVO.success(result);
        } catch (Exception e) {
            return ResultVO.clientError("获取分类热门图书失败: " + e.getMessage());
        }
    }

    /**
     * 获取新上架图书
     * @param page 页码
     * @param size 每页数量
     * @return 新上架图书列表
     */
    @GetMapping("/new")
    public ResultVO<PageVO<BookVO>> getNewBooks(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageVO<Book> newBooks = recommendationService.getNewBooks(page, size);
            
            // 转换为VO对象
            List<BookVO> bookVOList = newBooks.getList().stream()
                    .map(this::convertToBookVO)
                    .collect(Collectors.toList());
            
            PageVO<BookVO> result = new PageVO<>();
            result.setList(bookVOList);
            result.setTotal(newBooks.getTotal());
            // 设置页码和每页大小
            result.setPageNum(page);
            result.setPageSize(size);
            
            return ResultVO.success(result);
        } catch (Exception e) {
            return ResultVO.clientError("获取新上架图书失败: " + e.getMessage());
        }
    }

    /**
     * 获取分类下的新上架图书
     * @param categoryId 分类ID，可以是具体的分类ID或者特殊值"all"表示所有分类
     * @param page 页码
     * @param size 每页数量
     * @return 分类下的新上架图书
     */
    @GetMapping("/new/category/{categoryId}")
    public ResultVO<PageVO<BookVO>> getNewBooksByCategory(
            @PathVariable String categoryId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageVO<Book> newBooks;
            
            // 判断是否是特殊值"all"
            if ("all".equalsIgnoreCase(categoryId)) {
                // 获取所有分类的新上架图书
                newBooks = recommendationService.getNewBooks(page, size);
            } else {
                // 转换为Long类型并获取指定分类的新上架图书
                try {
                    Long categoryIdLong = Long.parseLong(categoryId);
                    newBooks = recommendationService.getNewBooksByCategory(categoryIdLong, page, size);
                } catch (NumberFormatException e) {
                    return ResultVO.clientError("分类ID格式不正确，应为数字或'all'");
                }
            }
            
            // 转换为VO对象
            List<BookVO> bookVOList = newBooks.getList().stream()
                    .map(this::convertToBookVO)
                    .collect(Collectors.toList());
            
            PageVO<BookVO> result = new PageVO<>();
            result.setList(bookVOList);
            result.setTotal(newBooks.getTotal());
            // 设置页码和每页大小
            result.setPageNum(page);
            result.setPageSize(size);
            
            return ResultVO.success(result);
        } catch (Exception e) {
            return ResultVO.clientError("获取分类新上架图书失败: " + e.getMessage());
        }
    }

    /**
     * 获取个性化推荐
     * @param userId 用户ID
     * @param page 页码
     * @param size 每页数量
     * @return 个性化推荐图书列表
     */
    @GetMapping("/personal/{userId}")
    public ResultVO<PageVO<BookVO>> getPersonalRecommendations(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageVO<Book> personalRecommendations = recommendationService.getPersonalRecommendations(userId, page, size);
            
            // 转换为VO对象
            List<BookVO> bookVOList = personalRecommendations.getList().stream()
                    .map(this::convertToBookVO)
                    .collect(Collectors.toList());
            
            PageVO<BookVO> result = new PageVO<>();
            result.setList(bookVOList);
            result.setTotal(personalRecommendations.getTotal());
            // 设置页码和每页大小
            result.setPageNum(page);
            result.setPageSize(size);
            
            return ResultVO.success(result);
        } catch (Exception e) {
            return ResultVO.clientError("获取个性化推荐失败: " + e.getMessage());
        }
    }

    /**
     * 获取相似图书
     * @param bookId 图书ID
     * @param page 页码
     * @param size 每页数量
     * @return 相似图书列表
     */
    @GetMapping("/similar/{bookId}")
    public ResultVO<PageVO<BookVO>> getSimilarBooks(
            @PathVariable Long bookId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageVO<Book> similarBooks = recommendationService.getSimilarBooks(bookId, page, size);
            
            // 转换为VO对象
            List<BookVO> bookVOList = similarBooks.getList().stream()
                    .map(this::convertToBookVO)
                    .collect(Collectors.toList());
            
            PageVO<BookVO> result = new PageVO<>();
            result.setList(bookVOList);
            result.setTotal(similarBooks.getTotal());
            // 设置页码和每页大小
            result.setPageNum(page);
            result.setPageSize(size);
            
            return ResultVO.success(result);
        } catch (Exception e) {
            return ResultVO.clientError("获取相似图书失败: " + e.getMessage());
        }
    }

    /**
     * 获取作者其他作品
     * @param authorId 作者ID
     * @param page 页码
     * @param size 每页数量
     * @return 作者其他作品列表
     */
    @GetMapping("/author/{authorId}")
    public ResultVO<PageVO<BookVO>> getAuthorOtherBooks(
            @PathVariable Long authorId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageVO<Book> authorBooks = recommendationService.getAuthorOtherBooks(authorId, page, size);
            
            // 转换为VO对象
            List<BookVO> bookVOList = authorBooks.getList().stream()
                    .map(this::convertToBookVO)
                    .collect(Collectors.toList());
            
            PageVO<BookVO> result = new PageVO<>();
            result.setList(bookVOList);
            result.setTotal(authorBooks.getTotal());
            // 设置页码和每页大小
            result.setPageNum(page);
            result.setPageSize(size);
            
            return ResultVO.success(result);
        } catch (Exception e) {
            return ResultVO.clientError("获取作者其他作品失败: " + e.getMessage());
        }
    }

    /**
     * 将Book实体转换为BookVO
     * @param book Book实体
     * @return BookVO对象
     */
    private BookVO convertToBookVO(Book book) {
        BookVO bookVO = new BookVO();
        bookVO.setId(book.getId());
        bookVO.setTitle(book.getTitle());
        bookVO.setAuthor(book.getAuthor());
        bookVO.setPublisher(book.getPublisher());
        bookVO.setPublishDate(book.getPublishDate());
        bookVO.setIsbn(book.getIsbn());
        bookVO.setLanguage(book.getLanguage());
        bookVO.setPrice(book.getPrice());
        bookVO.setPages(book.getPages());
        bookVO.setCoverUrl(book.getCoverUrl());
        bookVO.setDescription(book.getDescription());
        bookVO.setCatalog(book.getCatalog());
        bookVO.setRating(book.getRating());
        bookVO.setRatingCount(book.getRatingCount());
        bookVO.setFavoriteCount(book.getFavoriteCount());
        bookVO.setCommentCount(book.getCommentCount());
        bookVO.setReaderCount(book.getReadCount()); // 使用readerCount替代readCount
        bookVO.setSales(book.getSales());
        bookVO.setStock(book.getStock());
        bookVO.setStatus(book.getStatus());
        bookVO.setCreatedAt(book.getCreatedAt());
        bookVO.setUpdatedAt(book.getUpdatedAt());
        return bookVO;
    }
}
